package eu.winterwheels.enterprise.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

@ManagedBean(name = "i18n")
@SessionScoped
public class i18n implements Serializable {

	private static final long serialVersionUID = 1L;
	@Inject
	private FacesContext context;
	/**
	 * Default locale is set to "en". No country is set.
	 */
	private Locale currentLocale = Locale.ENGLISH;

	private List<Locale> availableLocales = new ArrayList<Locale>();

	/**
	 * Returns a list of available countries.
	 * 
	 * @return
	 */
	public List<Locale> getCountries() {

		if (!availableLocales.isEmpty())
			return availableLocales;
		else {
			synchronized (availableLocales) {
				Iterator<Locale> iter = context.getApplication().getSupportedLocales();
				while (iter.hasNext())
					availableLocales.add(iter.next());
			}
		}
		return availableLocales;
	}

	public String getCurrentLanguageCode() {
		return currentLocale.getLanguage();
	}

	public String getCurrentLanguageVariant() {
		return currentLocale.getDisplayVariant();
	}

	public void setLocaleByLanguage(String lang) {
		if (!lang.isEmpty() && lang.length() == 2) {
			this.currentLocale = new Locale(lang);
			FacesContext.getCurrentInstance().getViewRoot().setLocale(this.currentLocale);			
			FacesContext.getCurrentInstance().getApplication().setDefaultLocale(this.currentLocale);
		}
	}

}